define(function(require, exports, module) {

	var $ = require('jquery');
	var _ = require('underscore');
	var Backbone = require('backbone');


	// 列表模板
	var listPanelHtml = require('./tpl/list-panel.html');

	// 新建task模板
	var newTaskHtml = require('./tpl/new-task.html');

	var AssignmentUserWidget = require('../../widget/assignmentUserWidget');
	var TaskUsersWidget = require('../../widget/taskUsersWidget');
	var TaskListWidget = require('../../widget/taskListWidget');
	var TaskStatusWidget = require('../../widget/taskStatusWidget');

	var ListPanel = Backbone.View
			.extend({
				el : '#list-panel',
				task : null,
				tasklist : null,
				events : {
					'click .task-info' : 'detail',
					'keypress .new-task' : 'newTask',
					'click .task-status' : 'taskStatus',
					'click .task-users' : 'taskUsers',
					'click .task-date' : 'taskDate'
				},
				initialize : function() {
					this.task = Util.Models.get('task');
					this.tasklist = Util.Models.get('tasklist');

					this.getTaskList(Util.curProjectId);
				},
				taskDate : function(e) {
					e.preventDefault();
					e.stopPropagation();
					var taskDate = $(e.currentTarget);
					taskDate.datepicker('show').on('changeDate', function(ev) {
						taskDate.text(taskDate.data('date'));
						taskDate.datepicker('hide');
					});

				},
				taskUsers : function(e) {
					e.preventDefault();
					e.stopPropagation();
					var taskUsers = $(e.currentTarget);
					new TaskUsersWidget(taskUsers);

				},
				taskStatus : function(e) {
					e.preventDefault();
					e.stopPropagation();
					var taskStatus = $(e.currentTarget);
					var uuid = taskStatus.parent().parent().attr('data-id');
					new TaskStatusWidget(taskStatus,uuid);
//					
//					if (taskStatus.hasClass('icon-check-empty')) {
//						this.task.finish(uuid,function () {
//							taskStatus.removeClass('icon-check-empty').addClass(
//									'icon-check');
//						});
//					} else {
//						this.task.unfinish(uuid,function () {
//							taskStatus.removeClass('icon-check').addClass(
//									'icon-check-empty');
//						});
//					}
				},
				newTask : function(e) {
					if (e.keyCode == 13) {
						e.preventDefault();
						e.stopPropagation();
						var taskForm = $(e.currentTarget).parent();
						this.task.saveNewTask(taskForm.serialize(), $.proxy(
								this.successNewTask, this), $.proxy(this.error,
								this));
					}
				},
				successNewTask : function(newTask) {
					if(this.$el.find('.new-task-panel').is(":hidden")){
						this.$el.find('.new-task-panel').slideDown('slow');
					}
					
					this.$el.find('.new-task-panel').find('tbody').prepend(
							Util.tpl.t(newTaskHtml, newTask)).hide()
							.slideDown('slow');
					this.$el.find('.new-task').val("");
					this.$el.trigger('updateCommon');
				},
				/**
				 * 加载任务.  type,根据不同的type显示不同的类型的任务列表 "myTasklist":我的任务
				 * "tasklist":根据tasklistid显示任务列表 'userTasklist':显示某个用户的任务列表
				 */
				getTaskList : function(projectid, type, dataid) {
					if (_.isUndefined(type) || _.isNull(type)
							|| ('myTasklist' == type)) {// 显示我的任务
						this.task.getMyTaskList({
							projectid : projectid
						}, $.proxy(this.successTaskListByStatus, this));
					} else if ('tasklist' == type) {// 根据tasklistid显示任务列表
						this.task.getTasksByTasklistUuid({
							projectUuid : projectid,
							tasklistUuid : dataid
						}, $.proxy(this.successTaskListByStatus, this));
					} else {// 显示某个用户的任务列表
						this.task.getTasksByUserUuid({
							projectUuid : projectid,
							userUuid : dataid
						}, $.proxy(this.successTaskListByStatus, this));
					}
				},
				successTaskListByStatus : function(taskList, params) {//按照status分类 未开始0 进行中1 已完成2
					this.$el.html(Util.tpl.t(listPanelHtml, params));
					var tempList = this.task.filterByStatus(taskList.list,this.task.statusC.noBegin);
					var noBeginHtml = (new TaskListWidget($.extend({list:tempList.newList}, params,{title:'未开始的任务'}))).html();

					tempList = this.task.filterByStatus(taskList.list,this.task.statusC.doing);
					var doingHtml = (new TaskListWidget($.extend({list:tempList.newList}, params,{title:'正在进行中的任务'}))).html();
					
					tempList = this.task.filterByStatus(taskList.list,this.task.statusC.end);
					var endHtml = (new TaskListWidget($.extend({list:tempList.newList}, params,{title:'已经完成的任务'}))).html();
					
					this.$el.find('#list-wrapper').append(noBeginHtml+doingHtml+endHtml);

					this.$el.removeClass('show-detail-panel');
					this._clearActiveTaskdetail();
					this.$el.trigger('updateCommon');					
				},
				successTaskList : function(taskList, params) {
					this.$el.html(Util.tpl.t(listPanelHtml, params));

					var tempList = this.task.filterFinshedList(taskList.list);

					var finishedHtml = (new TaskListWidget($.extend({list:tempList.newList}, params,{title:'已经完成的任务'}))).html();

					tempList = this.task.filterTodayList(tempList.list);

					var todayHtml = (new TaskListWidget($.extend({list:tempList.newList}, params,{title:'今天的任务'}))).html();

					tempList = this.task.filterUnAssginDateList(tempList.list);

					var unAssginDateHtml = (new TaskListWidget($.extend({list:tempList.newList}, params,{title:'未指定日期的任务'}))).html();
					var sortByAssginDateList = this.task.filterSortByDate(tempList.list);

					var assginDateHtml = (new TaskListWidget($.extend({list:sortByAssginDateList}, params,{title:'时间排序的任务'}))).html();

					this.$el.find('#list-wrapper').append(todayHtml+assginDateHtml+unAssginDateHtml+finishedHtml);

					// taskList.list = this.task.filterUnAssginDateList(taskList.list);
					// console.log(taskList);

					this.$el.removeClass('show-detail-panel');
					this._clearActiveTaskdetail();
					this.$el.trigger('updateCommon');
				},
				detail : function(e) {
					var curTask = $(e.currentTarget);
					var taskId = curTask.attr('data-id');
					var tasklistId = curTask.attr('data-tasklist-id');
					var data={
						taskId:taskId,
						projectId:Util.curProjectId,
						tasklistId:tasklistId
					}
					if (this.$el.hasClass('show-detail-panel')) {
						if (curTask.hasClass('open-detail')) {
							this.$el.animate({
								width : '100%'
							});
							$('#detail-panel').animate({
								width : '0%'
							});
							this.$el.removeClass('show-detail-panel');
							this._clearActiveTaskdetail();
						} else {
							this._clearActiveTaskdetail();
							var detailPanel = Util.Views.get('detailPanel');
							detailPanel.getTask(data);
							curTask.addClass('open-detail')
						}
					} else {
						var detailPanel = Util.Views.get('detailPanel');
						detailPanel.getTask(data);
						this.$el.animate({
							width : '55%'
						});
						$('#detail-panel').animate({
							width : '45%'
						});
						this.$el.addClass('show-detail-panel');
						curTask.addClass('open-detail')
					}
				},
				_clearActiveTaskdetail : function() {// 清除task关联的detailpanel
					$('.task-info').each(function(index, val) {
						if ($(this).hasClass('open-detail')) {
							$(this).removeClass('open-detail');
							return;
						}
					});
				},
		        //删除任务后,同步删除列表中的数据
		        deleteTask:function(taskid){
		              this.$el.find('.task-info').each(function(){
		            	  if(taskid==$(this).attr('data-id')){
		            		  $(this).remove();
		            	  }
		              });
		        },
		        //更新任务后,同步更新列表中的数据
		        updateTask:function(result){
		        	 var self = this;
		              this.$el.find('.task-info').each(function(){
		            	  if(result.task.uuid==$(this).attr('data-id')){
		            	  	var tasklistId = $(this).attr('data-tasklist-id');
		            		  var html = Util.tpl.t(newTaskHtml, result);
		            		  $(this).html($(html).html()).show('slow');
		            		  self.$el.trigger('updateCommon');
		            	  }
		              });

		        }
			});

	module.exports = ListPanel;
})
